package com.yuanqi.service;

import com.yuanqi.repository.AccountRepository;
import com.yuanqi.repository.AccountsPayableRepository;
import com.yuanqi.repository.AccountsReceivableRepository;
import com.yuanqi.repository.PaymentRepository;
import com.yuanqi.repository.ReceiptRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

@Service
public class FinanceDashboardService {
    
    @Autowired
    private AccountRepository accountRepository;
    
    @Autowired
    private AccountsPayableRepository accountsPayableRepository;
    
    @Autowired
    private AccountsReceivableRepository accountsReceivableRepository;
    
    @Autowired
    private PaymentRepository paymentRepository;
    
    @Autowired
    private ReceiptRepository receiptRepository;
    
    public Map<String, Object> getDashboardData() {
        Map<String, Object> dashboardData = new HashMap<>();
        
        // 账户总余额
        Double totalBalance = accountRepository.getTotalBalance();
        dashboardData.put("totalBalance", totalBalance != null ? totalBalance : 0.0);
        
        // 应付账款统计
        Double totalPayable = accountsPayableRepository.getTotalUnpaidAmount();
        Double overduePayable = accountsPayableRepository.getTotalOverdueAmount();
        dashboardData.put("totalPayable", totalPayable != null ? totalPayable : 0.0);
        dashboardData.put("overduePayable", overduePayable != null ? overduePayable : 0.0);
        
        // 应收账款统计
        Double totalReceivable = accountsReceivableRepository.getTotalOutstandingAmount();
        Double overdueReceivable = accountsReceivableRepository.getTotalOverdueAmount();
        dashboardData.put("totalReceivable", totalReceivable != null ? totalReceivable : 0.0);
        dashboardData.put("overdueReceivable", overdueReceivable != null ? overdueReceivable : 0.0);
        
        // 本月付款统计
        LocalDate startOfMonth = LocalDate.now().withDayOfMonth(1);
        LocalDate endOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth());
        Double monthlyPayment = paymentRepository.getTotalPaymentAmount(startOfMonth, endOfMonth);
        dashboardData.put("monthlyPayment", monthlyPayment != null ? monthlyPayment : 0.0);
        
        // 本月收款统计
        Double monthlyReceipt = receiptRepository.getTotalReceiptAmount(startOfMonth, endOfMonth);
        dashboardData.put("monthlyReceipt", monthlyReceipt != null ? monthlyReceipt : 0.0);
        
        return dashboardData;
    }
}


